package cn.com.sbell.vss;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpHost;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HeaderElement;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.dom4j.Element;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.support.ClassPathXmlApplicationContext;



import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.io.InputStream;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.com.sbell.vss.VissSession;
import cn.com.sbell.vss.VssConstants;
import cn.com.sbell.vss.VssException;
import cn.com.sbell.vss.Response;
import cn.com.sbell.vss.servlet.DispatchServlet;


public class Network {
	private static final String RETURN_CODE_PATH = "/response/result/@code";
	private static final String RETURN_TEXT_PATH="/response/result";
	private static final String PARAMETERS_PATH = "/response/parameters";

	private static final String SUCCESS_CODE = "0";

	private static final Log log = LogFactory.getLog(Network.class);
	
public static Object[] sendRequestGetStr(String sessionId,String serverIp, int serverPort,String uri, 
		 NameValuePair[] nameValuePair,boolean throwErrors){
	HostConfiguration hconfig=new HostConfiguration();
	hconfig.setHost(new HttpHost(serverIp,serverPort));
	PostMethod post=new PostMethod();
	post.setPath(uri);
	post.addParameters(nameValuePair);
	if(null!=sessionId){
	post.setRequestHeader("Cookie", "sessionId="+sessionId);
	}
	Response response=null;
	int statusCode=0;
	HttpClient hclient =new HttpClient();
	SimpleHttpConnectionManager shcm=new SimpleHttpConnectionManager();
	HttpConnectionManagerParams hcmp=new HttpConnectionManagerParams();
	hcmp.setConnectionTimeout(60000);
	hcmp.setDefaultMaxConnectionsPerHost(1);
	hcmp.setLinger(60000);
	hcmp.setMaxTotalConnections(1);
	hcmp.setSoTimeout(60000);
	shcm.setParams(hcmp);
	hclient.setHttpConnectionManager(shcm);
	hclient.getParams().setContentCharset(VssConstants.DEFAULT_ENCODINIG);
	Object[] result=new Object[2];//result[0] for element parameter, and result[1] for nextHopSessionId
	Header[] cookie=null;
	
	try {
		statusCode=hclient.executeMethod(hconfig,post);
//		
		if(statusCode/100!=2)
		{
			if(throwErrors)
			throw new VssException(VssConstants.CODE_RELAY_ERROR);
		}
		response=getElement(post.getResponseBodyAsStream());
		result[0]=response;
		cookie=post.getResponseHeaders("Set-Cookie");
		for (int i = 0; i < cookie.length; i++) {
			HeaderElement[] piece=cookie[i].getElements();
			for (int j = 0; j < piece.length; j++) {
				if(piece[j].getName().equalsIgnoreCase("sessionId"))
				{
					result[1]=piece[j].getValue();
				}
			}
		}
	} catch (Exception e) {
		// TODO: handle exception
		if(throwErrors)
		throw new VssException(VssConstants.CODE_RELAY_ERROR);
	}finally{
	    post.releaseConnection();
	}
	
	
	
	return result;
	
}
public static NameValuePair[] makeNameValuePair(HttpServletRequest 
		 request,List include,List exclude) {
	Map map=request.getParameterMap();
	ArrayList result=new ArrayList();
//	if (log.isDebugEnabled())
//		log.debug("beging make name value, the reqeust map is:");
	for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) {
		Map.Entry element = (Map.Entry) iter.next();
//		if (log.isDebugEnabled())
//			log.debug(element.getKey()+","+element.getValue());
		String key=(String)element.getKey();
		if(exclude.contains(key))
		{
			continue;
		}
		String[] values=(String[])element.getValue();
		for (int i = 0; i < values.length; i++) {
			result.add(new NameValuePair(key,values[i]));
		}
		
			
	}
	for (Iterator iter = include.iterator(); iter.hasNext();) {
		NameValuePair element = (NameValuePair) iter.next();
		result.add(element);
		
	}
	return (NameValuePair[])result.toArray(new NameValuePair[0]);
}
public static Response getElement(InputStream in ){
SAXReader reader=new SAXReader();
Document doc=null;
Response response=new Response();
try {
	doc=reader.read(in);
	response.setReturnCode(doc.selectSingleNode(RETURN_CODE_PATH).getText());
	response.setReturnMessage(doc.selectSingleNode(RETURN_TEXT_PATH).getText());
	response.setParameters(doc.selectSingleNode(PARAMETERS_PATH));
} catch (Exception e) {
	// TODO: handle exception
	throw new VssException(VssConstants.CODE_RELAY_ERROR);
}
return response;
}
public static void main(String[] args) {
	ApplicationContext ctx=
		new ClassPathXmlApplicationContext("file:E:/files/jBossProject/CSG211ForChange/web-viss/WEB-INF/springframework/beans-message-common.xml");
	
	
//	MessageSource ms=(MessageSource)ctx;
	System.out.println(ctx.getMessage("code.4001", new Object[]{"[Vondart input]"},new Locale("zh_CN")));
}
}
